﻿using System.Web;
using StudentInfo.Security.Services;
using StudentInfo.Areas.AccountArea.Services;
using System.Web.Mvc;
using System.Web.Routing;
using StudentInfo.Security.Enums;

namespace StudentInfo.HtmlHelpers
{
    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString ActionLinkUsingPermissions(this HtmlHelper htmlHelper,
                                                               string linkText,
                                                               string action,
                                                               string controller,
                                                               object routeValues,
                                                               object attributes,
                                                               PermissionType required,
                                                               CrudType crud = CrudType.CanRead)
        {
            var account = AccountService.GetByName(HttpContext.Current.User.Identity.Name, true);
            if (account != null)
            {
                if (RolePermissionService.HasAccessByUser(account.Id, required, crud))
                {
                    var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
                    var anchorTagBuilder = new TagBuilder("a");
                    anchorTagBuilder.InnerHtml = linkText;
                    anchorTagBuilder.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
                    anchorTagBuilder.MergeAttributes(new RouteValueDictionary(attributes));
                    return MvcHtmlString.Create(anchorTagBuilder.ToString());
                }
            }

            return null;
        }

        public static MvcHtmlString ImageActionLink(this HtmlHelper htmlHelper,
                                                    string imgSrc,
                                                    string action,
                                                    object routeValues)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            string imgUrl = urlHelper.Content(imgSrc);
            var imgTagBuilder = new TagBuilder("img");
            imgTagBuilder.MergeAttribute("src", imgSrc);
            string img = imgTagBuilder.ToString(TagRenderMode.SelfClosing);

            var anchorTagBuilder = new TagBuilder("a") { InnerHtml = img };
            anchorTagBuilder.Attributes["href"] = urlHelper.Action(action, routeValues);
           
            return new MvcHtmlString(anchorTagBuilder.ToString(TagRenderMode.Normal));
        }
    }
}